<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
class yiYuanService extends MY_Service {
    
    public $aid;
    public $title;
    public $ids;
    public $content;
    public $gcid;
    public $thumb;
    public $orderId;
    public $gid;
    public $type;
    public $money;
    public $cycle;
    
    public function __construct($data) {
        parent::__construct();
        $this->aid = $data['aid'];
    }
    
    
    
    /**
     * 
     * 保存晒单
     */
    public function saveSendShare() {
        $this->load->model('yygoods_cycle_model', 'mgoodsc');
        $info = $this->mgoodsc->get_one($this->gcid);
        if (empty($info)) {
            exit(json_encode(array('errno' => 1, 'msg' => '获取活动数据失败')));
        }
         
        $photo = substr($this->ids, 0, strlen($this->ids) - 1); 
        
        $savadata = array(
            'gid' => $info['gid'],
            'aid' => $this->aid,
            'status' => $info['status'],
            'cycle' => $info['cycle'],
            'content' => $this->content,
            'thumb' => $this->thumb,
            'photo' => $photo,
            'orderId' =>$this->orderId,
            'timeline' => time(),
            'title' => $this->title
        );   
        $this->load->model('yygoods_comment_model', 'commentModel');
        $resut = $this->commentModel->create($savadata);
        if (empty($resut)) {
            exit(json_encode(array('errno' => 1, 'msg' => '上传失败')));
        }
    }

    /**
     *  检查
     */
    public function checkSendShare() {
        if (empty($this->title)) {
            exit(json_encode(array('errno' => 1, 'msg' => '请填写标题')));
        }
        if (empty($this->content)) {
            exit(json_encode(array('errno' => 1, 'msg' => '请填写内容')));
        }
        if (empty($this->ids)) {
            exit(json_encode(array('errno' => 1, 'msg' => '请上传图片')));
        }
        if (empty($this->thumb)) {
            exit(json_encode(array('errno' => 1, 'msg' => '缩略图参数为空')));
        }
        if (empty($this->gcid)) {    
            exit(json_encode(array('errno' => 1, 'msg' => 'gcid参数丢失')));
        }
        if (empty($this->orderId)) {  
            exit(json_encode(array('errno' => 1, 'msg' => 'orderId参数丢失')));
        }
        if (empty($this->gid)) {  
            exit(json_encode(array('errno' => 1, 'msg' => 'gid参数丢失')));
        }
    }
    
    
//    public function qianggouComment($gcid) {
//        if (!is_numeric($gcid)) {
//            show_404();
//            return false;
//        }
//        $this->load->model('yygoods_cycle_model', 'mgoodsc');
//        $data = $this->mgoodsc->get_one($gcid);
//        return $data['gid'];
//    }
     
    public function qianggouComment_ajax($gid,$page = 1){       
        $this->load->model('yygoods_comment_model', 'mgoodsc');
        $info = $this->mgoodsc->get_list_two(8,($page-1)*8,false,array('gc.gid' => $gid));
        if(!empty($info)){
            return $this->clPhoto($info); 
        }
        return '';
    }
    
    public function qianggouComment_info($id) {
        $this->load->model('yygoods_comment_model', 'mgoodsc');
        $it = $this->mgoodsc->get_list_two(1, 0, false, array('gc.id' => $id)); 
        if(!empty($it)){
            $d = $this->clPhoto($it);
        } 
        return $d[0] ? $d[0] : '';
    }
    
    
    public function evaluateInfo($orderId) {
        $this->load->model('yygoods_comment_model', 'comment');
        $list = $this->comment->getCommentList($orderId);
        if (!empty($list)) {
            $list = $this->clPhoto($list);
            return $list[0] ? $list[0] : '';
        }
        return '';
    }

    /**
     * 处理评论表查询出来的图片字符串
     * @param type $info
     */
    public function clPhoto($info) {
        $arr = array();
        $this->load->model('upload_model', 'upload');
        foreach ($info as $v) {
            //for循环查数据库,暂时用
            $v['photos'] = $this->upload->get_in($v['photo']);
            $arr[] = $v;
        }
        unset($v);
        return $arr ? $arr : '';
    }
    
    //更新订单状态
    public function updateStatus(){
        $this->load->model('yyorder_model', 'yyorder');
        $this->yyorder->updateStatus($this->orderId); 
        exit(json_encode(array('errno'=>0,'msg'=>'晒单成功','url'=>site_url('myCenter/goods/'.$this->gid))));
    }
    
    
    public function result($gcid){  
        $this->load->model('yygoods_cycle_model', 'cycle');
        $where = 'gc.id = '.$gcid.' and gr.aid = '.$this->aid;
        $data = $this->cycle->getResult(8,0,false,$where);

        if (!empty($data)) {
            $data = $data[0];
            if ($data['gc_status'] == 1) {
                $this->load->model('yygoods_record_model', 'record');
                $list = $this->record->get_all('aid = ' . $data['gc_aid'] . ' and gcid = ' . $data['gc_id']);
                $data['prize_codes'] = $list[0]['codes'];
            }
            //获取下一期正在进行的期数
            $nextCycle = $this->cycle->get_one_p(array('status'=>0,'gid'=>$data['gid']));
            $data['nextCycleId'] = $nextCycle['id'];
            $data['nextCycle'] = $nextCycle['cycle'];
        }
        return $data ? $data : '';
    }
    
    /**
     * 
     * @param type $gid
     */
    public function periods($gid,$n = ''){
        $this->load->model('yygoods_cycle_model', 'cycle');
        
        if(empty($n)){
            $where = array('gid'=>$gid);
            $list = $this->cycle->get_all($where,'*',array('cycle'=>'desc'),false);
        }else{
            $num = 50;
            $start = $num * ($n  - 1) + 1;
            $end = $num*$n;
            $where = 'gid = '.$gid.' and cycle >= '.$start.' and cycle <= '.$end;
            $list = $this->cycle->get_all($where,'*',array('cycle'=>'desc'));
        }
        return $list ? $list : '';  
    }
    
    /**
     * 
     * @param type $gcid
     */
    public function compute($gcid){
        $this->load->model('yygoods_cycle_model', 'cycle');
        $where = 'gc.id = '.$gcid;
        $list = $this->cycle->compute(10,0,false,$where);
        if(!empty($list)){
            $returnData = $this->getResult($list);
        }
        return $returnData ? $returnData : '';
    }  
    
    
    /**
     * 
     * @param type $list
     */
    public function getResult($list){
        
        $numA = $numB = $numResult = '';
        $returnData = array();
        foreach ($list as $v){
            $clTime = $this->clTime($v['gr_timeline']);
            $numA += $clTime;
            $v['clTime'] = $clTime;
            $returnData[] = $v;
        }

        $otherCode = $list[0]['other_code'];
        if(empty($otherCode)){
            logfile('彩票第三方数据为空','error');
            return '';
        }
        
        $numB = preg_replace('/[,]+/i','',$otherCode);  
        $numResult = ($numA + $numB) % $list[0]['money'] + 10000001;    //(数值A+数值B)/总需人次得到的余数 + 10000001
       
        return array('list'=>$returnData,'numA'=>$numA,'numB'=>$numB,'numResult'=>$numResult);
    }
    
    /**
     * 
     * @param type $time = '1447074439.052'->"2015-11-09 21:07:19" return "210719052"
     * @return type
     */
    public function clTime($time) {
        $t = explode('.', $time);
        $t1 = date('H:i:s', $t[0]);
        $t2 = preg_replace('/[:]+/i', '', $t1);
        return $t2 . $t[1];
    }
    
    
    public function createPeople($userList){
           $str = '';
           if(!empty($userList)){
                foreach ($userList as $k => $u){
                    $style = $this->aid == $u['aid'] ? 'cur' : '';
                    $str .= '<div data-n="'.($k + 1).'" class="img por db fl '.$style.'"><p><img src="'.$u['a_thumb'].'" alt=""></p><span class="num dib">'.($k + 1).'</span></div>';
                   // $codes .= $k ? ','.$u['codes'] : $u['codes'];
                }
           }
           return $str;
    }
    
    /**
     * 大转盘抽奖
     * @param type $gid
     * @param type $type
     */
    public function lotteryPay(){
        //获取用户信息
         $this->load->model('account_model', 'maccpay');
         $user = $this->maccpay->getinfo(array('id' => $this->aid));
        
         //检查条件
         $this->checkLotteryPay($user);
         
         //购买  
         $this->load->model('action_model', 'maction');
         $rs = $this->maction->payAwards($this->gid,$this->aid,$this->money,$this->type);
         if(empty($rs)||$rs['returnNo'] == 0){
             exit(json_encode($rs));
         }
         //返回数据
         $this->returnData($user,$rs);
    }
    
    
    public function checkLotteryPay($user) {  
        if ($user['money'] < 1) {
            exit(json_encode(array('returnNo' => 0, 'returnInfo' => '抽奖失败，账户余额不足'))); // 余额不足
        }
        $this->load->model('yyawards_record_model', 'record');
        $info = $this->record->get_one('gid = '.$this->gid.' and aid = '.$this->aid.' and cycle = '.$this->cycle);
        
        if(!empty($info)){
            $this->load->model('yyawards_result_model', 'result');
            $r = $this->result->get_one('gid = '.$this->gid.' and cycle = '.$this->cycle);
            if(empty($r)){
                exit(json_encode(array('returnNo' => 0, 'returnInfo' => '当前还未开奖,不能重复参与！！')));  //如果已经参与,并且当前期数还未开奖
            }
        }
    }
    
    public function returnData($user,$rs) {
        $nickname = $user['nickname'] ? $user['nickname'] : substr_replace($user['mobile'], '****', 3, 4);

        $vdata['userinfo'] = array('nickname' => $nickname, 'thumb' => $user['thumb']);
        $vdata['returnNo'] = 1;
        $vdata['cycle'] = $rs['cycle'];
        $vdata['returnInfo'] = '抽奖成功';
        exit(json_encode($vdata));
    }
    
    public function getLotteryResult(){
        $this->load->model('yyawards_record_model', 'record');
        $list = $this->record->getLotteryResult('gr.gid = '.$this->gid.' and gr.cycle = '.$this->cycle);
        
        $people = $this->createPeople($list);
        
        $is_begin = 0; //开奖条件
        if(count($list) >= $this->type){
            //获取用户信息
            $is_begin = 1;
            $this->load->model('yyawards_result_model', 'result');
            $user = $this->result->getPrizeUser('r.gid = '.$this->gid.' and r.cycle = '.$this->cycle);
            if(!empty($user)){
                $nickname = isset($user[0]['a_nickname']) ? $user[0]['a_nickname'] : ubstr_replace($user[0]['a_mobile'], '****', 3,4);
                $vdata['winner'] = array('code'=>$user[0]['r_code'],'thumb'=>$user[0]['a_thumb'],'nickname'=>$nickname);
            }
            
            //开奖后写入自己已读状态
            $this->load->model('yyawards_record_model', 'record');
            foreach ($list as $v){
                //自己的记录
                if($v['gr_aid'] == $this->aid){
                    $this->record->updateRead($v['gr_id']);
                }
            }
            
        }
        $vdata['returnNo'] =1;
        $vdata['is_begin'] = $is_begin;
        $vdata['people'] = $people;
        exit(json_encode($vdata));
    }
    
    /**
     * 
     * @param type $gid
     */
    public function lotteryInfo($gid) {
        //商品信息
        $this->load->model('yyawards_model', 'yyawards');
        $vdata['it'] = $this->yyawards->get_one(array('id'=>$gid));
        // 获取用户信息
        $this->load->model('account_model', 'account');
        $vdata['user'] = $this->account->getinfo(array('id' => $this->aid));

        // 今日抽奖人数
        $this->load->model('yyawards_record_model', 'record');
        $vdata['count'] = $this->record->get_count_all(array('gid'=>$gid,'timeline >' => strtotime(date('Y-m-d'))));
        //目前采取精准数据
        //$vdata['count'] = $count ? $count : rand(0, 200) + $count;
        
        //用户最新参与的一期
        $info = $this->record->get_one(array('gid' => $gid, 'aid' => $this->aid), 'id,gid,codes,cycle');  
        $vdata['cycle'] = isset($info['cycle']) ? $info['cycle'] : 1;//如果不存在默认第一期
        //是否等待界面
        if($this->isInter($info,intval($vdata['it']['money']))){
            $vdata['isInter'] = 1;
        }else{
            $vdata['isInter'] = 0;
        }
        return $vdata;
    }
    
    /**
     * 判断用户是否可以进入房间
     * @param type $gid
     */
    public function isInter($info, $type) {
        if (empty($info)) {
            return false;   //用户没有参与
        }
        
        //查询开奖数据
        $this->load->model('yyawards_result_model', 'result');
        $result = $this->result->get_one('gid = ' . $info['gid'] . ' and cycle = ' . $info['cycle']);
        //$sql = $this->db->last_query();
        if (!empty($result)) {
            return false;   //如果当期已经开奖
        }
        return true;
    }

}
